var express = require('express')
const sqlQuery = require('../../../module/sqlQuery')
const { resJsonObject } = require('../../../module/canshu')

var router = express.Router()

/* GET users listing. */
router.get('/', async function (req, res, next) {
  res.render('admin/users/authlist')
})

router.get('/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let { page, limit, keywords = '' } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery(
      'select * from auth where authname like ? limit ?,?',
      ['%' + keywords + '%', (page - 1) * 5, limit]
    )

    // 符合条件的总条数
    const [
      { count_num },
    ] = await sqlQuery(
      'select count(*) as count_num from auth where authname like ?',
      ['%' + keywords + '%']
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

router.get('/roledata', async function (req, res, next) {
  let { roleid = 0 } = req.query

  const results = await sqlQuery('select * from auth')

  if (roleid === 0) {
    return res.json(
      resJsonObject({
        code: 0,
        msg: '获取所有权限列表成功',
        data: {
          count: results.length,
          results,
        },
      })
    )
  } else {
    const hadAuthList = await sqlQuery(
      'select auth.id as authid from role_auth ,auth WHERE role_auth.roleid=? AND auth.id=role_auth.authid',
      [parseInt(roleid)]
    )

    return res.json(
      resJsonObject({
        code: 0,
        msg: '获取所有权限列表成功',
        data: {
          count: results.length,
          results,
          hadAuthList,
        },
      })
    )
  }
})

router.get('/add', (req, res, next) => {
  res.render('admin/users/addAuth.ejs')
})

router.post('/add', async (req, res, next) => {
  try {
    let { authname, authurl } = req.body

    // authlist = JSON.parse(authlist)

    await sqlQuery('insert into auth (authname,authurl) values (?,?)', [
      authname,
      authurl,
    ])

    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from auth where id=?`

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { authinfo: results[0] }
  res.render('admin/users/editAuth.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  console.log(req.body)
  const { authname, authurl, authid } = req.body
  await sqlQuery(
    `update auth 
    set authname=?,
    authurl=?
    where id=?`,
    [authname, authurl, authid]
  )
  res.json(
    resJsonObject({
      code: 0,
      msg: '更新成功',
    })
  )
})

// 用户信息删除
router.post('/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  try {
    // 用户信息删除（update状态改位为 0 ）
    // const { username, password, email, mobile, roleid } = req.body

    const results = await sqlQuery('delete from auth where id=?', [
      parseInt(id),
    ])

    res.json(
      resJsonObject({
        code: 0,
        msg: '删除成功',
      })
    )
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '删除失败',
        data: {
          error,
        },
      })
    )
  }
})

module.exports = router
